// stores/userStore.ts
import {
  types,
  Instance,
  destroy,
  flow,
} from 'mobx-state-tree';
import { persist } from 'mst-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { login, setToken } from '@/utils/request/Api';
import { router } from 'expo-router';

const UserModel = types
  .model('UserStore', {
    token: types.maybe(types.string),
    username: types.maybe(types.string),
    userId: types.maybe(types.string),
    isAuthenticated: false,
    lang: types.maybe(types.string),
  })
  .actions((self) => ({
    setUserLang(payload: { lang: string; }){
      self.lang = payload.lang;
    },
    login: flow(function* (companyId: string, loginName: string, loginPassword: string) {
      const params = { 
        company_id: companyId,
        login_name: loginName,
        login_password: loginPassword,
        system_from: 'H',
        phone_type: 'IOS',
        device_token: '',
      };

      try {
        const response = yield login(params);
        self.token = response.token;
        self.isAuthenticated = true;
        // 登入成功的api模塊注入token
        setToken(response.token);
        router.replace('/(tabs)');
      } catch (error) {
        console.error('Login failed:', error);
        throw error;
      }
    }),
    logout() {
      self.isAuthenticated = false;
      self.token = '';
      self.userId = '';
      self.username = '';
      self.lang = 'en';
      // 登出要取消api模塊token
      setToken(null);
      router.replace('/login');
    },
  }))
  .views((self) => ({
    get currentUser() {
      return {
        username: self.username,
        userId: self.userId,
      };
    },
  }));

// 创建持久化配置
const createPersistStore = () => {
  const store = UserModel.create();

  // 配置持久化
  persist('userStore', store, {
    storage: AsyncStorage, // React Native 的 AsyncStorage
    jsonify: true, // 启用 JSON 序列化
    whitelist: ['token', 'username', 'userId', 'isAuthenticated', 'lang'], // 需要持久化的字段
  });

  return store;
};

export type UserStoreType = Instance<typeof UserModel>;
export const userStore = createPersistStore();
